/**
 * 
 */
package za.co.sindi.oauth.core.scanner;

import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.apache.log4j.Logger;

import za.co.sindi.oauth.core.scanner.filter.TypeFilter;

/**
 * @author Buhake Sindi
 * @since 26 March 2012
 *
 */
public abstract class AbstractClassScanner implements ClassScanner {

	protected static final String JAVA_CLASS_EXTENSION = ".class";
	protected static final String JAVA_JAR_EXTENSION = ".jar";
	protected final Logger logger = Logger.getLogger(this.getClass());
	
	private List<TypeFilter> includeFilters;
	private List<TypeFilter> excludeFilters;
	
	/* (non-Javadoc)
	 * @see com.neurologic.oauth.resource.scanner.ClassScanner#addIncludeFilter(com.neurologic.oauth.resource.scanner.filter.TypeFilter)
	 */
	@Override
	public void addIncludeFilter(TypeFilter filter) {
		// TODO Auto-generated method stub
		if (includeFilters == null) {
			includeFilters = new ArrayList<TypeFilter>();
		}
		
		includeFilters.add(filter);
	}
	
	/* (non-Javadoc)
	 * @see com.neurologic.oauth.resource.scanner.ClassScanner#addExcludeFilter(com.neurologic.oauth.resource.scanner.filter.TypeFilter)
	 */
	@Override
	public void addExcludeFilter(TypeFilter filter) {
		// TODO Auto-generated method stub
		if (excludeFilters == null) {
			excludeFilters = new ArrayList<TypeFilter>();
		}
		
		excludeFilters.add(filter);
	}
	
	protected boolean match(Class<?> clazz) {
		if (excludeFilters != null) {
			for (TypeFilter excludeFilter : excludeFilters) {
				if (excludeFilter.match(clazz)) {
					return false;
				}
			}
		}
		
		if (includeFilters != null) {
			for (TypeFilter includeFilter : includeFilters) {
				if (includeFilter.match(clazz)) {
					return true;
				}
			}
		}
		
		//There's no include/exclude filters, default (accept everything)
		return true;
	}
	
	/**
	 * Read the JAR file and adds classes that matches our {@link TypeFilter}.
	 * 
	 * @param jarURL
	 * @param packagePath
	 * @param classes
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	protected void readJarEntries(URL jarURL, String packagePath, Set<Class<?>> classes) throws IOException, ClassNotFoundException {
		JarURLConnection jarConn = (JarURLConnection) jarURL.openConnection();
		JarFile jarFile = jarConn.getJarFile();
		Enumeration<JarEntry> entries = jarFile.entries();
		while (entries != null && entries.hasMoreElements()) {
			JarEntry entry = entries.nextElement();
			if (entry.isDirectory()) continue;
			
			String name = entry.getName();
			if (!name.startsWith(packagePath) || name.equals(packagePath)) continue;
			
			name = name.substring(packagePath.length());
			if (name.contains("/")) continue;
			
			if (name.endsWith(JAVA_CLASS_EXTENSION)) {
				URLClassLoader classLoader = new URLClassLoader(new URL[] {jarURL});
				Class<?> clazz = classLoader.loadClass(entry.getName().substring(0, entry.getName().length() - JAVA_CLASS_EXTENSION.length()));
				if (match(clazz)) {
					if (logger.isInfoEnabled()) {
						logger.info("Found matched class '" + clazz.getName() + "' in JAR '" + jarURL.getPath() + "'. Adding to set.");
					}
					classes.add(clazz);
				}
			}
		}
	}
}
